package com.tencent.qf.common.config;

import com.tencent.qf.common.config.properties.SpecialAreaPoolProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import javax.annotation.Resource;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author: p_haojiawu@tencent.com
 * @date: 2023-03-06
 **/
@EnableAsync
@Slf4j
@Configuration
public class SpecialAreaThreadPoolConfig {

    @Resource
    private SpecialAreaPoolProperties specialAreaPoolProperties;

    @Bean("asyncSpecialAreaExecutor")
    public Executor asyncSendMessageExecutor() {
        log.info("start asyncSendMessageExecutor");
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(specialAreaPoolProperties.getCoreSize());
        executor.setMaxPoolSize(specialAreaPoolProperties.getMaxSize());
        executor.setQueueCapacity(specialAreaPoolProperties.getQueueSize());
        executor.setKeepAliveSeconds(specialAreaPoolProperties.getKeepAliveSeconds());
        executor.setThreadNamePrefix("async-special-area-");
        // rejection-policy：当pool已经达到max size的时候，如何处理新任务
        // CALLER_RUNS：不在新线程中执行任务，而是由调用者所在的线程来执行
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();
        return executor;
    }
}
